package org.jie.guider.network.netty.telnet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author LiJie
 */
public class TelnetClient {

    public static void main(String[] args)
        throws InterruptedException, IOException {
        String ip = "localhost";
        int port = 8083;
        EventLoopGroup worker = new NioEventLoopGroup(5);

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new TelnetClientHandler());
                }
            });
        Channel channel = bootstrap.connect(ip, port).sync().channel();
        ChannelFuture lastWriteFuture = null;
        BufferedReader in =
            new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String line = in.readLine();
            if (Objects.isNull(line)) {
                break;
            }
            lastWriteFuture = channel.writeAndFlush(line);

            if ("exit".equals(line.toLowerCase())) {
                break;
            }
        }
        channel.closeFuture().sync();
        if (Objects.nonNull(lastWriteFuture)) {
            lastWriteFuture.sync();
        }
        worker.shutdownGracefully();
    }
}
